import buildQueryString from '@/utils/buildQueryString';
import type { ActionType, ProColumns } from '@ant-design/pro-components';
import { PageContainer, ProTable } from '@ant-design/pro-components';
import { useModel } from '@umijs/max';
import { Button, message } from 'antd';
import moment from 'moment';
import React, { useEffect, useRef, useState } from 'react';
import type { CreateUserProps } from '../DyCps/components/CreateUserDrawer';
import { fetchChannelUser } from '../DyCps/service';
import CreateUserDrawer from './components/CreateUserDrawer';
import UpdateFormDy from './components/UpdateFormDy';
import { createDyCpsChannel, getHistoryOrders, saveFlowOrders } from './service';

const handleUpdateOrders = async (selectedRows: any) => {
  const hide = message.loading('正在更新');
  try {
    const rsp = await saveFlowOrders({ ...selectedRows });
    if (rsp.data.upType === 'view') {
      if (rsp.data.url === 'true') {
        message.success('跟单成功');
      } else {
        message.error('跟单失败');
      }
    } else {
      window.open(rsp.data.url);
    }
    //
    hide();

    return true;
  } catch (error) {
    hide();
    message.error('跟单失败');
    return false;
  }
};
const handleCreateChannel = async (selectedRows: any) => {
  const hide = message.loading('正在更新');
  try {
    await createDyCpsChannel({ ...selectedRows });
    hide();
    message.success('更新成功');
    return true;
  } catch (error) {
    hide();
    message.error('更新失败');
    return false;
  }
};

const orderStatuses = [
  {
    label: '创建',
    value: 0,
  },
  {
    label: '支付',
    value: 10,
  },
  {
    label: '退款',
    value: 20,
  },
  {
    label: '部分退款',
    value: 21,
  },
  {
    label: '结算',
    value: 30,
  },
  {
    label: '确认收货',
    value: 40,
  },
];
const cpsConf = [
  {
    label: 'YF_2',
    value: 'cps_zbj_yf2',
  },
  {
    label: 'YF_3',
    value: 'cps_zbj_yf3',
  },
  {
    label: 'YF_4',
    value: 'cps_zbj_yf4',
  },
  {
    label: 'YF_5',
    value: 'cps_zbj_yf5',
  },
  {
    label: 'YF_6',
    value: 'cps_zbj_yf6',
  },
  {
    label: 'YF_7',
    value: 'cps_zbj_yf7',
  },
  {
    label: 'APP_2',
    value: 'CPS-ZBJ-yf2',
  },
  {
    label: 'APP_3',
    value: 'CPS-ZBJ-yf3',
  },
  {
    label: 'APP_4',
    value: 'CPS-ZBJ-yf4',
  },
  {
    label: 'APP_5',
    value: 'CPS-ZBJ-yf5',
  },
  {
    label: 'APP_6',
    value: 'CPS-ZBJ-yf6',
  },
  {
    label: 'APP_7',
    value: 'CPS-ZBJ-yf7',
  },
];
const timeTypes = [
  {
    label: '订单创建时间',
    value: 1,
  },
  {
    label: '订单更新时间',
    value: 2,
  },
  {
    label: '订单支付时间',
    value: 3,
  },
];
const TableList: React.FC = () => {
  const { initialState } = useModel('@@initialState');
  const { currentUser } = initialState || {};
  const [requestStatus] = useState(currentUser?.userInfo?.role !== 'super');
  const [channelStatus] = useState(currentUser?.userInfo?.role === 'normal');
  const actionRef = useRef<ActionType>();
  const [dateRange, setDateRange] = useState<any>();
  const [updateOrdersVisible, handleUpdateOrdersVisible] = useState<boolean>(false);
  const [createChannelVisible, handleCreateChannelVisible] = useState<boolean>(false);
  const [currentOrderRow, setCurrentOrderRow] = useState<CreateUserProps>();
  const [count, setCount] = useState<number>(0);
  const [amount, setAmount] = useState<number>(0);
  const [timeType, setTimeType] = useState<any>(3);
  /**
   * @en-US International configuration
   * @zh-CN 国际化配置
   * */
  useEffect(() => {
    const startOfDay = new Date(new Date());
    startOfDay.setHours(0, 0, 0, 0);
    const endOfDay = new Date(new Date()).setHours(23, 59, 59, 0);
    setDateRange([startOfDay, endOfDay]);
  }, []);

  const columns: ProColumns<any>[] = [
    {
      title: '媒体APP',
      dataIndex: 'cps',
      valueType: 'select',
      hideInTable: true,
      hideInSearch: requestStatus,
      request: async () => {
        return cpsConf;
      },
    },
    {
      title: '订单查询时间类型',
      dataIndex: 'timeType',
      valueType: 'select',
      hideInTable: true,
      request: async () => {
        return timeTypes;
      },
      fieldProps: {
        value: timeType,
        onChange: (val) => {
          setTimeType(val);
        },
      },
    },

    {
      title: '产品店铺',
      dataIndex: 'storeName',
      copyable: true,
    },
    {
      title: '商品详情',
      dataIndex: 'itemName',
      copyable: true,
    },
    {
      title: '订单号',
      dataIndex: 'orderId',
      valueType: 'textarea',
      copyable: true,
    },
    {
      title: '下单链接',
      dataIndex: 'appLink',
      valueType: 'textarea',
      copyable: true,
    },
    {
      title: '直播间',
      dataIndex: 'roomName',
      valueType: 'textarea',
      copyable: true,
    },
    {
      title: '订单件数',
      dataIndex: 'itemNum',
      valueType: 'textarea',
      hideInSearch: true,
    },
    {
      title: '单用户下单数',
      dataIndex: 'requestOrderCount',
      valueType: 'textarea',
      hideInSearch: true,
    },
    {
      title: '支付金额',
      dataIndex: 'totalPayAmount',
      hideInSearch: true,
      renderText: (text) => {
        return text / 100;
      },
    },
    {
      title: '渠道',
      dataIndex: 'channel',
      valueType: 'select',
      hideInSearch: requestStatus,
      hideInTable: channelStatus,
      request: async () => {
        const data = await fetchChannelUser({});
        return [...data.data, { label: '无', value: 0 }];
      },
    },

    {
      title: '订单支付时间',
      dataIndex: 'payTime',
      valueType: 'dateTime',
      hideInSearch: true,
    },
    {
      title: '订单退款时间',
      dataIndex: 'refundTime',
      valueType: 'dateTime',
      hideInSearch: true,
    },
    {
      title: '订单结算时间',
      dataIndex: 'settlementTime',
      valueType: 'dateTime',
      hideInSearch: true,
    },
    {
      title: '订单状态',
      dataIndex: 'orderStatus',
      valueType: 'select',

      request: async () => {
        return orderStatuses;
      },
    },
    {
      title: '后台佣金比例',
      dataIndex: 'rate',
      hideInTable: requestStatus,
      hideInSearch: true,
      renderText: (text) => {
        return text / 100 + '%';
      },
    },
    {
      title: '渠道佣金比例',
      dataIndex: 'proRate',
      hideInTable: requestStatus,
      hideInSearch: true,
      renderText: (text) => {
        return text / 100 + '%';
      },
    },
    {
      title: '佣金比例',
      dataIndex: 'subRate',
      hideInSearch: true,
      renderText: (text) => {
        return text / 100 + '%';
      },
    },
    {
      title: '订单支付时间',
      dataIndex: 'orderDate',
      valueType: 'dateRange',
      hideInForm: true,
      hideInTable: true,
      search: {
        transform: (value) => {
          return {
            startTime: value[0],
            endTime: value[1],
          };
        },
        fieldProps: {
          value: dateRange,
          onChange: (value: any) => {
            if (value && value.length === 2) {
              setDateRange(value);
            }
          },
        },
      },
    },
  ];

  return (
    <PageContainer>
      <ProTable<API.RuleListItem, API.PageParams>
        headerTitle={'全部订单: /总支付金额：' + count + '/ 预估佣金：' + amount}
        actionRef={actionRef}
        rowKey="key"
        toolBarRender={() => [
          initialState?.currentUser?.userInfo?.role === 'super' ? (
            <Button
              key="2"
              type="primary"
              onClick={() => {
                handleCreateChannelVisible(true);
              }}
            >
              创建渠道
            </Button>
          ) : (
            ''
          ),
          initialState?.currentUser?.userInfo?.role === 'super' ||
          initialState?.currentUser?.userInfo?.role === 'admin' ? (
            <Button
              key="2"
              type="primary"
              onClick={() => {
                handleUpdateOrdersVisible(true);
              }}
            >
              跟单
            </Button>
          ) : (
            ''
          ),
        ]}
        search={{
          defaultCollapsed: false,
          labelWidth: 100,
          optionRender: ({ searchText, resetText }, { form }) => {
            return [
              <Button
                key="reset"
                style={{ marginRight: '10px' }}
                onClick={() => {
                  actionRef?.current?.reset();
                }}
              >
                {resetText}
              </Button>,
              <Button key="search" type="primary" htmlType="submit" style={{ marginRight: '10px' }}>
                {searchText}
              </Button>,
              !channelStatus ? <Button
                key="export"
                type="primary"
                onClick={() => {
                  const startTime = moment(new Date(dateRange[0])).format('YYYY-MM-DD HH:mm:ss');
                  const endTime = moment(new Date(dateRange[1]).setHours(23, 59, 59, 0)).format(
                    'YYYY-MM-DD HH:mm:ss',
                  );
                  const fieldData = form.getFieldsValue();
                  let params = {
                    startTime,
                    exportType: 'order_list',
                    token: localStorage.getItem('token'),
                    endTime,
                    ...fieldData,
                  };
                  let str = buildQueryString(params);
                  window.open('/api/exportDyFile' + str);
                }}
              >
                导出
              </Button> : '',
            ];
          },
        }}
        request={async (params: any) => {
          const defaultValues = columns.reduce((acc, column) => {
            if (column.fieldProps && column.fieldProps.value !== undefined) {
              acc[column.dataIndex] = column.fieldProps.value;
            }
            return acc;
          }, {});

          const startTime = moment(new Date(dateRange[0])).format('YYYY-MM-DD HH:mm:ss');
          const endTime = moment(new Date(dateRange[1]).setHours(23, 59, 59, 0)).format(
            'YYYY-MM-DD HH:mm:ss',
          );
          // 将默认值合并到请求参数中
          const data = { ...params, ...defaultValues, startTime, endTime };
          const rsp = await getHistoryOrders(data);
          if (rsp.code === 'SUCCESS') {
            setCount(rsp.data.count);
            setAmount(rsp.data.amount);
            return {
              data: rsp.data.list,
              total: rsp.data.total,
              success: true,
            };
          }
        }}
        columns={columns}
      />
      <UpdateFormDy
        onSubmit={async (value) => {
          // console.log(value);
          // return;
          const success = await handleUpdateOrders({ ...value });
          if (success) {
            handleUpdateOrdersVisible(false);
            setCurrentOrderRow(undefined);
            if (actionRef.current) {
              actionRef.current.reload();
            }
          }
        }}
        onUpdate={async (value) => {
          handleUpdateOrdersVisible(false);
          setCurrentOrderRow(undefined);
          if (actionRef.current) {
            actionRef.current.reload();
          }
          window.open(value);
        }}
        onCancel={() => {
          handleUpdateOrdersVisible(false);
          setCurrentOrderRow(undefined);
        }}
        updateModalVisible={updateOrdersVisible}
        values={currentOrderRow || {}}
        formType={0}
      />
      <CreateUserDrawer
        onSubmit={async (value) => {
          // return;
          const success = await handleCreateChannel({ ...value });
          if (success) {
            handleCreateChannelVisible(false);
            if (actionRef.current) {
              actionRef.current.reload();
            }
          }
        }}
        onCancel={() => {
          handleCreateChannelVisible(false);
        }}
        updateModalVisible={createChannelVisible}
        values={{}}
        formType={0}
      />
    </PageContainer>
  );
};
export default TableList;
